<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2019 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\agency\controller;


use app\agency\service\NodeService;
use app\common\facade\Arr;
use library\Controller;
use library\tools\Data;
use think\Console;
use think\Db;
use think\exception\HttpResponseException;
use app\common\facade\TransItem;
use app\common\services\JobService;
use app\common\services\PublishJobService;
use app\common\services\JobOptionService;
use app\common\tools\ExportExcel;

/**
 * 兼职管理
 * Class Index
 * @package app\agency\controller
 */
class Job extends AgentBase
{
    public $table = 'Jobs';

    /**
     * 兼职概况
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
        //获取当前代理商所在城市
        $user=$this->agentUser;
        $data['provinces_id']=$user['provinces_id'];
        $data['city_id']=$user['city_id'];

        $result['total'] = Db::name('Jobs')->where($data)->where('status!=0')->count();//全部兼职
        $result['beaudite']=Db::name('Jobs')->where($data)->where('status=1')->count();//待审核
        $result['pass']=Db::name('Jobs')->where($data)->where('status=2')->count();//审核通过兼职
        $result['deny']=Db::name('Jobs')->where($data)->where('status=3')->count();//审核拒绝
        $result['work']=Db::name('Jobs')->where($data)->where('status=4')->count();//工作中兼职
        $result['complete']=Db::name('Jobs')->where($data)->where('status=5')->count();//已完成兼职
        $this->assign('result',$result);
        $this->fetch();

    }

    /**
     * 兼职列表
     * @auth true
     * @menu true
     * @throws \ReflectionException
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function jobList(){

        $this->title = '兼职列表';
        $status = $this->request->param('status', 0);
        if($status!=0&&!empty($status)){
            $data[]=['status','EQ',$status];
            if($status==1){
                $this->title = '待兼职列表';
            }elseif ($status==2) {
                $this->title = '审核通过兼职列表';
            }elseif ($status==3) {
                $this->title = '审核拒绝兼职列表';
            }elseif ($status==4) {
               $this->title = '工作中兼职列表';
            }else{
                $this->title = '已完成兼职列表';
            }
        }else{
            $data[]=['status','NEQ',$status];
        }

        $result=$this->agentUser;
        $data[]=['provinces_id','EQ',$result['provinces_id']];
        $data[]=['city_id','EQ',$result['city_id']];


        $work_type=DB::name("JobsType")->field("id,name")->select();
        $this->assign('work_type',$work_type);
        $query = $this->_query($this->table)
            ->where($data)
            ->like('title')
            ->equal('id,mobile,work_type,is_top,contacts');
        $query->order('id desc')->page();



    }
    /**
     * 数据列表处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _jobList_page_filter(&$data)
    {

        $this->clist = Db::name('JobsType')->field("id,name")->select();
        foreach ($data as &$vo) {
            $vo['salary_unitCh'] = TransItem::transMoneyUnit(Arr::get($vo, 'salary_unit'));
            $vo['settlement_typeCh'] = TransItem::transSettlement(Arr::get($vo, 'settlement_type'));
            $vo['province'] = DB::name("Area")->where('area_id',$vo['provinces_id'])->value("area_name");
            $vo['city'] = DB::name("Area")->where('area_id',$vo['city_id'])->value("area_name");
            $vo['add_time'] = date("Y-m-d",$vo['created_at']);
            foreach ($this->clist as $cate) if ($cate['id'] === $vo['work_type']) $vo['cate'] = $cate;

        }
    }


    /**
     * 编辑详情
     * @auth true
     */
    public function editJob()
    {
        if ($this->request->isGet()) {

            $jobId = $this->request->param('id', 0);
            $extend = "content,userApply";
            $extend = array_filter(explode(',', $extend));
            $result=(new JobService())->jobDetail($jobId,$extend);
            $result['work_time']=date("Y-m-d",$result['work_time']);
            $result['work_time_end']=date("Y-m-d",$result['work_time_end']);
            $result['created_at']=date("Y-m-d H:i:s",$result['created_at']);
            $this->assign('result',$result);

            //兼职类型
            $jobtype=Db::name('JobsType')
                ->field("id,name")
                ->where('status=1')->select();
            $this->assign('jobtype',$jobtype);

            //薪资单位
            $salary_unit= TransItem::transMoneyUnit();
            $this->assign('salary_unit',$salary_unit);

            //工作状态
            $jobstatus= TransItem::transJobApply();
            $this->assign('jobstatus',$jobstatus);

            //结算方式
            $settlement= TransItem::transSettlement();
            $this->assign('settlement',$settlement);

            $this->title ='编辑兼职|兼职编号：'.$result['id'];
            if($result['admin_id']==0){
                $user=DB::name("User")->where('id',$result['user_id'])->field("truename,mobile")->find();
                $this->title ='编辑兼职|兼职编号：'.$result['id']."|注册人：".$user['truename']."|联系电话：".$user['mobile'];
            }
            $this->fetch('edit_job');

        }else{
            $data=$this->request->post();
            if($postData['salary']<=0){
                $this->error("请输入薪资待遇！");
            }
            $postData['content']=$data['content'];
            $postData['requirement']=$data['requirement'];
            $postData['work_welfare']=$data['work_welfare'];
            $postData['updated_at']=time();
            $result = Db::name('jobs_content')
                        ->where('job_id', $data['job_id'])
                        ->update($postData);
            //后台兼职可以修改相关信息
            if(!empty($data['admin_id'])){
               $job_data['title']=$data['title'];
               $job_data['work_type']=$data['work_type'];
               $job_data['salary']=$data['salary'];
               $job_data['salary_unit']=$data['salary_unit'];
               $job_data['need_worker']=$data['need_worker'];
               $job_data['contacts']=$data['contacts'];
               $job_data['mobile']=$data['mobile'];
               $job_data['address']=$data['address'];

               $time=$this->request->param('work_time');
                $time_work=explode(' - ',$time);
                $job_data['work_time']=strtotime($time_work[0]);
                $job_data['work_time_end']=strtotime($time_work[1]);
               $job_data['work_up_time']=$data['work_up_time'];
               $job_data['work_down_time']=$data['work_down_time'];
               $job_data['settlement_type']=$data['settlement_type'];
               $job_data['gender']=$data['gender'];
               $job_data['is_top']=$data['is_top'];
               $job_data['is_recommend']=$data['is_recommend'];
               $job_data['updated_at']=time();
               $result = Db::name('jobs')
                        ->where('id', $data['job_id'])
                        ->update($job_data);


            }
            if($result){
                $this->success('修改成功！','javascript:history.back()');
            }else{
                $this->error('修改失败！');
            }
        }
    }
    /**
     * 审核兼职
     * @auth true
     */
    public function auditJob(){

        $jobId = $this->request->param('id', 0);
        $pass = $this->request->param('status', 0);
        $publishJobService = new PublishJobService();
        if($pass==1){
            //审核通过
            $result = $publishJobService->approvedJob($jobId,$this->userId);
            if($result){
                $this->success('操作成功');
            }else{
                $this->error('操作失败');
            }
        }else{
            $message=$this->request->param('replay');
            if(empty($message)){
                $this->error('请输入拒绝理由');
            }else{
                $result = $publishJobService->rejectJob($jobId, $this->userId, $message);
                if($result){
                    $this->success('操作成功');
                }else{
                    $this->error('操作失败');
                }
            }
        }
    }

    public function deny(){
        $this->title = '审核拒绝兼职';
        $this->assign('id',$this->request->param('id', 0));
        $this->fetch('deny');
    }
    /**
    * 添加兼职
    * @auth true
    * @auth true
    */
    public function job_add()
    {   
        
        if($this->request->isGet()){
            $this->title = '添加兼职';
            //获取当前代理商所在城市
            $user=$this->agentUser;
            //兼职类型
            $jobtype = Db::name('JobsType')
                    ->where('status=1')
                    ->field("id,name")
                    ->select();
            $this->assign('jobtype',$jobtype);

            //薪资单位
            $salary_unit= TransItem::transMoneyUnit();
            $this->assign('salary_unit',$salary_unit);

            //工作状态
            $jobstatus= TransItem::transJobApply();
            $this->assign('jobstatus',$jobstatus);

             //结算方式
            $settlement= TransItem::transSettlement();
            $this->assign('settlement',$settlement);

            //获取代理商所在省份城市
            $address['province']=DB::name("Area")->where('area_id',$user['provinces_id'])->value('area_name');
            $address['city']=DB::name("Area")->where('area_id',$user['city_id'])->value('area_name');
            $this->assign('address',$address);

            //获取代理商所在所有区域
            $county=DB::name("Area")->where('area_parent_id',$user['city_id'])->field('area_name')->select();
            $this->assign('county',$county);
            

            $this->fetch();
        }else{
            
            $postData=$this->request->param();
            if($postData['salary']<=0){
                $this->error("请输入薪资待遇！");
            }
            if($postData['salary_unit']==1000){
                $this->error("请输入薪资单位！");
            }

            //获取当前代理商所在城市2021-01-01-2020-01-19
            $user=$this->agentUser;
            $postData['user_id']=$user['bind_agent_user_id'];

            $time=$this->request->param('work_time');
            $time_work=explode(' - ',$time);

            $postData['admin_id']=$this->userId;
            $postData['work_time']=strtotime($time_work[0]);
            $postData['work_time_end']=strtotime($time_work[1]);
            $postData['provinces_name']=$postData['province']." ".$postData['city']." ".$postData['county'];
            $publishJobService = new PublishJobService();

            $result = $publishJobService->publishJob($postData);
            if($result){
                $this->success('添加成功','javascript:history.back()');
            }else{
                $this->error('添加失败');
            }
            
        }

    }
    /**
    * 报名列表
    * @auth true
    * 
    */
    public function apply(){

        $jobId = $this->request->param('id', 0);
        $query = $this->_query("JobsApply")
            ->where('job_id',$jobId)
            ->like('title')
            ->equal('status');
        $query->order('id desc')->page();
    }
    /**
     * 数据列表处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _apply_page_filter(&$data)
    {

        foreach ($data as &$vo) {
            $vo['user'] = DB::name("UserExtend")->where('user_id',$vo['user_id'])->field("true_name,mobile")->find(); 
            $vo['add_time']=date("Y-m-d H:i",$vo['created_at']);
            $vo['jstatus'] = TransItem::transJobApply(Arr::get($vo, 'status'));
        }
      

    }

    /**
     * 报名审核
     * @auth true
     */
    public function auditApply(){

        $data['applyId'] = $this->request->param('id', 0);
        $data['jobId'] = $this->request->param('jobid', 0);
        $data['status'] = $this->request->param('status', 0);

        $JobOptionService = new JobOptionService();
        if($data['status']==2){
            //审核通过
            $result = $JobOptionService->auditUserApplyJob($data);
            if($result){
                $this->success('操作成功');
            }else{
                $this->error('操作失败');
            }
        }else{
            $data['message']=$this->request->param('content');
            if(empty($data['message'])){
                $this->error('请输入拒绝理由');
            }else{
                 $result = $JobOptionService->auditUserApplyJob($data);
                if($result){
                    $this->success('操作成功');
                }else{
                    $this->error('操作失败');
                }
            }
        }
    }

   /**
     * 结束招聘
     * @auth true
     */
    public function close(){

        $jobid = $this->request->param('id', 0);
        $jobinfo=DB::name("jobs")->where('id',$jobid)->find();
        $JobOptionService = new JobOptionService();
        $result=$JobOptionService->closeApplyJob($jobinfo,0,1);
        if($result){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }

    /**
     * 完成工作
     * @auth true
     */
    public function done(){

        $jobid = $this->request->param('id', 0);
        $jobinfo=DB::name("jobs")->where('id',$jobid)->find();
        $JobOptionService = new JobOptionService();
        $result=$JobOptionService->doneJob($jobinfo);
        if($result){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }

    public function applyDeny(){
        $this->title = '审核拒绝报名';
        $result=$this->request->param();
        $this->assign('result',$result);
        $this->fetch('apply_deny');
    }

     //兼职置顶
    public function top(){
        $top = $this->request->param('top');
        $this->_save($this->table, ['is_top' => $top]);
    }

     //兼职推荐
    public function recommend(){
        $is_recommend = $this->request->param('is_recommend');
        $this->_save($this->table, ['is_recommend' => $is_recommend]);
    }




    /**
     * 导出报名表
     * @auth true
     */
    public function export(){

        $jobid = $this->request->param('id', 0);
        $job=DB::name("Jobs")->where('id',$jobid)->field("title,work_time")->find();
        $title="兼职标题|".$job['title']."|兼职时间|".date("Y-m-d",$job['work_time']);
        $data = Db::name('JobsApply')->alias('j')
            ->where('j.job_id', $jobid)
            ->join('jobs js', 'js.id = j.job_id')
            ->join('UserExtend ue', 'j.user_id = ue.user_id')
            ->field('js.title as jobName,ue.true_name as user_true_name,ue.mobile as user_mobile,j.status,j.created_at')
            ->select();
        foreach ($data as $key => $value) {
           $result[$key]['jobName']=$value['jobName'];
           $result[$key]['true_name']=$value['user_true_name'];
           $result[$key]['mobile']=$value['user_mobile'];
           $result[$key]['jstatus'] = TransItem::transJobApply(Arr::get($value, 'status'));
           $result[$key]['add_time']=date("Y-m-d H:i",$value['created_at']);
        }

        $exportdata = [
            'cellTitle'     => [
                [
                    'name'      => '兼职标题',
                    'dataName'  => 'jobName',
                ],
                [
                    'name'      => '姓名',
                    'dataName'  => 'true_name',
                ],
                [
                    'name'      => '联系电话',
                    'dataName'  => 'mobile',
                ],
                [
                    'name'      => '状态',
                    'dataName'  => 'jstatus',
                ],
                [
                    'name'      => '报名时间',
                    'dataName'  => 'add_time',
                ]
            ],
            'list'          => $result,
            'otherExportList'     => [
                [
                    'sheetIndex'    => 1,
                    'sheetTitle'    => "$title",
                    'list'  => $result,
                    'cellTitle'     => [
                        [
                            'name'      => '兼职标题',
                            'dataName'  => 'jobName',
                        ],
                        [
                            'name'      => '姓名',
                            'dataName'  => 'true_name',
                        ],
                        [
                            'name'      => '联系电话',
                            'dataName'  => 'mobile',
                        ],
                        [
                            'name'      => '状态',
                            'dataName'  => 'jstatus',
                        ],
                        [
                            'name'      => '报名时间',
                            'dataName'  => 'add_time',
                        ]
                    ],
                ]
            ]
        ];
        (new ExportExcel())->exportDataToXls(
            "$title",
            $exportdata
        );
    }




}
